﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.Composition;
using System.Diagnostics.Contracts;
using System.IO;
using System.Reflection;
namespace DynamicDnsChanger.Extensions.DynDNS
{
    [Export(typeof(IUpdater))]
    public class CloudFlare : IPlugin, IUpdater
    {
        private readonly IRequester _Requester;

        public string Name
        {
            get { return "CloudFlare"; }
        }

        public event EventHandler<InfoStatus> StatusChange;
        [ImportingConstructor]
        public CloudFlare(IRequester Requester)
        {

            Contract.Requires(Requester != null, "IRequester");
            this._Requester = Requester;
        }
        public void Update(string NewIP)
        {
            Contract.Requires(StatusChange != null, "StatusChange");
            
            var email = "";
            var token = "";
            var zone = "";
            var domains = "";
            var iniFilePath = String.Concat(new FileInfo(Assembly.GetExecutingAssembly().Location).Directory, @"\DynamicDnsChanger.Extensions.CloudFlare.ini");
            //var iniFilePath = "DynamicDnsChanger.Extensions.CloudFlare.ini";
            if (!File.Exists(iniFilePath))
            {
                this.StatusChange.Invoke(this, new InfoStatus(TypeOfMessage.Error, "Arquivo não localizado: " + iniFilePath));
                return;
            }
            using (var iniFile = new StreamReader(iniFilePath))
            {
                var strLine = iniFile.ReadLine();

                while (strLine != null)
                {
                    var pair = strLine.Split('=');
                    if (pair.Count() > 1)
                    {
                        if (pair[0].Trim() == "email")
                        {
                            email = pair[1].Trim();
                        }
                        else if (pair[0].Trim() == "zone")
                        {
                            zone = pair[1].Trim();
                        }
                        else if (pair[0].Trim() == "token")
                        {
                            token = pair[1].Trim();
                        }
                        else if (pair[0].Trim() == "domains")
                        {
                            domains = pair[1].Trim();
                        }
                    }
                    strLine = iniFile.ReadLine();
                }
            };//exemplo.com
            //Cada linha de domains_info deve conter  o nome do subdominio da zona a ser alterado ex. api [api.exemplo.com]
            //o id do subdomino (deve ser obtido em 
            //https://www.cloudflare.com/api_json.html?tkn=YOUR_TOKEN&email=YOUR_EMAIL&a=rec_load_all&z=YOUR_ZONE)
            // e o tipo de entrada do dns (A/AAAA/CNAME) separados por dois pontos ":"
            // exemplo "api:147316048:A" - subdomain = api - id = 147316048 - tipo = A
            
            foreach (var siteinfo in domains.Split(';'))
            {

                var info = siteinfo.Split(':');

#if DEBUG
                             Console.WriteLine(siteinfo);
                info = "api:149436343".Split(':');//Não alterar os outros hosts enquanto estiver na depuração
#endif

                var clouflareApiUrl = "https://www.cloudflare.com/api_json.html?tkn={0}&email={1}&a=rec_edit&z={2}&type=A&id={3}&name={4}&content={5}&service_mode=0&ttl=1";
                var r = _Requester.GetString(String.Format(clouflareApiUrl, token, email, zone, info[1], info[0], NewIP));
                StatusChange.Invoke(this, new InfoStatus(r.Contains("success") ? TypeOfMessage.Success : TypeOfMessage.Error, r.Contains("success") ? String.Format("domain: {0}.{1} > IP: {2}", info[0], zone, NewIP) : r));
            }
        }
    }
}
